import { BrowserWindow, ipcMain, globalShortcut } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import os from 'os'

let win

const createWindow = async function () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 1280,
    minHeight: 800,
    show: true,
    transparent: true,
    titleBarStyle: 'customButtonsOnHover',
    hasShadow: true,
    frame: false, // 是否显示顶部导航栏
    center: true,

    webPreferences: {

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true
    }
  })

  win.on('closed', () => {
    win = null
  })

  // 快捷键的注册-打开调试框
  globalShortcut.register('CTRL+SHIFT+I', () => {
    if (win) win.webContents.openDevTools()
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(`${process.env.WEBPACK_DEV_SERVER_URL}/main.html`)
    // 本地测试，打开调试框
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    // createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./main.html')
  }
}

const getWindow = function () {
  return win
}

// 窗口最小化
ipcMain.on('main-win-min', function () {
  win.minimize()
})

// 登录窗口最大化
ipcMain.on('main-win-narrow', function () {
  if (os.type() === 'Darwin') {
    win.setFullScreen(false)
  } else {
    win.unmaximize()
  }
})

// 登录窗口最大化
ipcMain.on('main-win-max', function () {
  if (os.type() === 'Darwin') {
    win.setFullScreen(true)
  } else {
    win.maximize()
  }
})

// 隐藏窗口
ipcMain.on('main-win-hide', function () {
  win.close()
})

// 关闭窗口
ipcMain.on('window-close', function (event, msg) {
  setTimeout(() => {
    win.webContents.send('setPrinter', ['list'])
  }, 3000)
})

// win.webContents.send('chat-show', '')

export default {
  createWindow,
  getWindow
}
